package com.gientech.framework.common.utils;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * @author gang.tu
 * @ClassName UpdateUtil
 * @Description
 * @Date 2022/11/11 11:33
 */
public class UpdateUtil {


    /**
     * @description 返回空值
     * @author gang.tu
     * @date 2022/11/11 11:34
     * @return: java.lang.String[]
     */
    public static String[] getNullPropertyNames(Object source) {
        Set<String> emptyNames = getEmptyNames(source);
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * @description 返回空值-过滤指定的值
     * @author gang.tu
     * @date 2022/11/11 11:34
     * @return: java.lang.String[]
     */
    public static String[] getNullPropertyNames(Object source, Set<String> ignores) {
        Set<String> emptyNames = getEmptyNames(source);
        emptyNames.removeAll(ignores);
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * @description 获取空字段
     * @author gang.tu
     * @date 2022/11/11 11:40
     * @return: java.util.Set<java.lang.String>
     */
    private static Set<String> getEmptyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        return emptyNames;
    }
}